<template>
  <div class="new_div1">
    <el-dialog
      v-model="dialogVisibles"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      width="60%"
      draggable
      @close = "share_cancel"
    >
      <template #header>
        <div class="addressDiv">
          <div class="customerTitle2">地址簿</div>
<!--          <el-button type="primary" size="small"  @click="share_save">导入</el-button>-->
        </div>
      </template>
      <div>
        <div class="addressDiv1">
        <div style="padding-bottom:10px">
          收货地址批量识别
          <span class="addressFont1">
             粘贴整段地址到下方输入框，将自动拆分姓名、电话和详细地址，多条地址间用【；】分隔开
          </span>
        </div>
         <div>
           <VabUploadFile :query="{ customer_uid: customerId }" api="/api/dms/customer/location/import" @Refresh="() => {
            ElMessage({
              message: '导入成功',
              type: 'success',
            })//刷新页面
            customerList()
          }"/>
         </div>
        </div>
          <div class="border ">
            <el-input
              class="width_100"
              :autosize="{ minRows: 3, maxRows: 4 }"
              v-model.trim="pasteAddress"
              placeholder="例如：王小二，137xxxx1234，山东省青岛市崂山区协信中心1号楼14层（批量识别暂不支持港澳台、国际地址）"
            />
            <div class="flex_just_end" style="margin-top: 12px">
              <el-button
                size="small"
                type="primary"
                @click="identify(pasteAddress)"
              >
                识别
              </el-button>
              <el-button size="small" @click="empty" >
                清空
              </el-button>
            </div>
          </div>
        <div>
          <el-table
            border
            :data="addressList"
            height="450px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" align="center" width="80">
              <template #default="props">
                <div class="table_style">
<!--                  <label class="el-checkbox"
                         :class="{ 'is-checked': radioIndex === props.row.id }"
                         @click="handleRadio(props.row)"
                  >
                    <span class="el-checkbox__input" :class="{ 'is-checked': radioIndex == props.row.id }"><span class="el-checkbox__inner"></span></span>
                  </label>-->
                  <span style="margin-left: 5px"
                        v-text="(props.$index + 1)"
                  ></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="shipping_contact" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  联系人
                </span>
              </template>
              <template #default="props">
                <el-input v-model.trim="props.row.shipping_contact" />
              </template>
            </el-table-column>
            <el-table-column prop="shipping_tel" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  联系电话
                </span>
              </template>
              <template #default="props">
                <el-input v-model.trim="props.row.shipping_tel" />
              </template>
            </el-table-column>
            <el-table-column prop="province" align="center" min-width="200" >
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  省/市/区
                </span>
              </template>
              <template #default="props">
                <el-cascader
                  placeholder=" "
                  ref="address_ref"
                  v-model="props.row.shipping_address"
                  :options="areaOption"
                  style="width:100%;display: inline-block"
                  :props="{ value: 'name', label: 'name' }"
                >
                  <template #default="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="address" align="center" min-width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                 详细地址
                </span>
              </template>
              <template #default="props">
                <el-input v-model.trim="props.row.address" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="70">
              <template #default="props">
                <vab-icon
                  icon="add-circle-line"
                  class="icon_color"
                  @click="handleClickAdd(props.row)"
                />
                <vab-icon
                  v-if="addressList.length>1"
                  icon="delete-bin-5-line"
                  @click="handleClickRemove(props.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer customerDialog3">
            <el-button @click="share_cancel">取消</el-button>
          <el-button type="primary"  @click="share_save">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import lodash from "lodash";
import {addressParse} from "/@/api/dms/address";
import {ElMessage, ElMessageBox} from "element-plus";
import {customerLocationList, orderLocationSave} from "/@/api/dms/customer/location";
import {ref} from "vue";
import {areaOptions} from "/@/views/corpManagement/corpCustomers/tools";

const areaOption = ref<any>([])
const dialogVisibles = ref(false)
const pasteAddress = ref(null)
const addressList = ref<any>([])
let selectAddress =  ref(undefined)
const route:any = useRoute()
const customerId = ref(undefined)
// 表格校验
const check = ()=>{
  const product_list = addressList.value
  const  check1 =  product_list.map((item:any,index:any)=>{
    if(item.shipping_contact == '' || item.shipping_contact == undefined){
      ElMessage.warning(`序号为 ${index +1}联系人名称 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check2 =  product_list.map((item:any,index:any)=>{
    if(item.shipping_tel == '' || item.shipping_tel == undefined){
      ElMessage.warning(`序号为 ${index +1}联系人电话 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check3 =  product_list.map((item:any,index:any)=>{
    if(item.shipping_address == '' || item.shipping_address == undefined){
      ElMessage.warning(`序号为 ${index +1}省/市/区 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check8 =  product_list.map((item:any,index:any)=>{
    if(item.address == '' || item.address == undefined){
      ElMessage.warning(`序号为 ${index +1}信息地址 不能为空`)
      return false
    }else {
      return true
    }
  })
  const check6 = [...check1,...check2,...check3,...check8].every(i=>i==true)
  return check6
}
// *******提交 取消********
const share_save = lodash.debounce( async (va:any)=>{
if( !check())return
  orderLocationSave({customer_uid:customerId.value ,address_list:addressList.value.map((item:any)=>{return{...item,shipping_address:item.shipping_address.toString()}})}).then(()=>{
    if( route.query.path == 3 || route.query.path == 4 ){
      if(multipleDate.value.length  == 1) {
        selectAddress.value = multipleDate.value
        dialogVisibles.value= false
        ElMessage.success(`提交成功`)
        multipleDate.value = []
      }else{
        ElMessage.error(`请选择地址,并且只能选择一条地址`)
      }
    }else {
      selectAddress.value = multipleDate.value
      dialogVisibles.value= false
      ElMessage.success(`提交成功`)
      multipleDate.value = []
    }
  })
  /*if( route.query.title == 1 || route.query.title == 2 ){
    if(multipleDate.value.length  == 1) {
      selectAddress.value = multipleDate.value
      dialogVisibles.value= false
      ElMessage.success(`提交成功`)
      multipleDate.value = []
    }else{
      ElMessage.error(`只能选择一条地址`)
    }
  }else {
    selectAddress.value = multipleDate.value
    dialogVisibles.value= false
  }*/
},500)
const share_cancel = ()=>{
  multipleDate.value = []
  dialogVisibles.value= false
}
// ********添加地址 删除地址*************
const handleClickAdd =(row:any)=>{
  const newObject = {id:String(new Date().getTime()).slice(-6),shipping_contact:'',shipping_tel:'',shipping_address:'',address:''}
  // productList.value.push({id:String(new Date().getTime()).slice(-6),sales_num:0,goods_no:'',flag:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'正品',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]})
  const insertIndex = addressList.value.findIndex((item:any)=> item.id === row.id) + 1;
  addressList.value.splice(insertIndex, 0, newObject)
}
const handleClickRemove = (row:any)=>{
  ElMessageBox.confirm(
    '删除该收货信息，各系统该客户的收货地址信息会同步删除，请确认是否删除?',
    {
      confirmButtonText: '确定',
      cancelButtonText: '返回',
      type: 'warning',
    }
  )
    .then(() => {
      addressList.value =  addressList.value.filter((item:any)=>item.id != row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })


}
//获取联系人列表
const customerList = ()=>{
  customerLocationList({customer_uid:customerId.value}).then((data:any)=>{
    if(data.code == 200 && data.data.list.length > 0){
      addressList.value = data.data.list.map((item:any)=> {return{...item,shipping_address:item.shipping_address.split(",")}})
    }else {
      addressList.value = [{id:0,shipping_contact:'',shipping_tel:'',shipping_address:'',address:''}]
    }
  })
}
watch(customerId,()=>{
  if(customerId){
    customerList()
  }
})
// 识别
const identify = async (va:string)=>{
  if(va != null && va!=''&& va){
    await addressParse({address:va}).then((data:any)=>{
      if(data.code == 200){
        const arr = data.data.map((value:any,index:number)=>{
          return{
            id:String(new Date().getTime()).slice(-6)+index,
            shipping_contact:value.name,
            shipping_tel:value.mobile,
            shipping_address:[value.province,value.city,value.district],
            address:value.detail,
          }
        })
        addressList.value = [...addressList.value,...arr]
        ElMessage.success(`识别成功`)
        pasteAddress.value = null
      }
    })
  }else {
    ElMessage.warning(`识别不能为空`)
  }
}
// 清空
const empty = ()=>{
  pasteAddress.value = null
  /*  await addressParse({address:''}).then((data:any)=>{
      console.log(data)
    })*/
}
// 单选
const radioIndex = ref(null)
const handleRadio = (row: any) => {
  radioIndex.value = row.id
}
// 多选
let multipleDate = ref<any>([])
const handleSelectionChange = (val: any, va: any) => {
  multipleDate.value = val
  // multipleDate1 = val
}
//抛出数据
defineExpose({
  dialogVisibles,
  selectAddress,
  customerId,
})
onMounted(async ()=>{
  // 获取地址
  areaOption.value = await areaOptions()
})
</script>

<style lang="scss" scoped>
@import "../index";
.border {
  margin-bottom: 10px;
  width: 100%;
  border: 1px solid rgba(192, 196, 204, 0.6);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  border-radius: 5px;
  transition: var(--el-transition-box-shadow);
  transform: translate3d(0, 0, 0);
  padding: 4px;
  &:hover {
    border: 1px solid rgba(192, 196, 204, 0.8);
  }
  :deep() {
    .el-input__wrapper {
      box-shadow: none;
    }
    .el-input__wrapper:hover {
      box-shadow: none;
    }
  }
}
</style>

